package com.jht.mymvvm.activity.dbpage

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.jht.mymvvm.R
import com.jht.mymvvm.db.AppDatabase
import com.jht.mymvvm.db.dao.UserDao
import com.jht.mymvvm.db.entity.User
import kotlinx.android.synthetic.main.activity_db.*

private const val TAG = "DbActivity"
class DbActivity : AppCompatActivity(), View.OnClickListener {

    private lateinit var userDao:UserDao

    private val user1 = User("chen","cheng",23,"cc")
    private val user2 = User("chen2","cheng2",22,"gg")


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_db)
        userDao = AppDatabase.getDatabase(this).userDao()
        getUserBtn.setOnClickListener(this)
        addDataBtn.setOnClickListener(this)
        updateDataBtn.setOnClickListener(this)
        deleteDataBtn.setOnClickListener(this)
        queryDataBtn.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.updateDataBtn -> {
                user1.firstName = "只给你问"
                userDao.updateUser(user1)
            }
            R.id.getUserBtn -> {
                userDao.loadUsersOlderThan(12).forEach{
                    Log.d(TAG, "onClick: ${it.firstName + " " + it.lastName + "; age:" + it.age}  ")
                }
            }
            R.id.addDataBtn -> {
                user1.id = userDao.insertUser(user1)
                user2.id = userDao.insertUser(user2)
                Log.d(TAG, "onClick: insert id user1 = ${user1.id} , and user2 = ${user2.id}")
            }
            R.id.deleteDataBtn -> {
                userDao.deleteUserByLastName("cheng2")
            }
            R.id.queryDataBtn -> {
                userDao.loadAllUsers().forEach {
                    Log.d(TAG, "onClick: ${it.firstName + " " + it.lastName + "; age:" + it.age}  ")
                }
            }
        }

    }
}